<template>
  <div class="">
    <Navbar></Navbar>
    <el-row style="margin-top: 80px;border-bottom: 2px solid #f4f4f5;padding-bottom: 60px">
      <el-col offset="2" span="15">
        <span style="font-size: 50px">网上商城</span>
      </el-col>
<!--      <el-col span="4">-->
<!--        <el-input style="width: 73%;height: 40px"></el-input>-->
<!--        <el-button style="width: 26%;margin-left: 1%;height: 40px">搜索</el-button>-->
<!--      </el-col>-->
    </el-row>
    <el-row style="margin-top: 40px;padding: 0 200px" v-for="category of categories" :key="category.id">
      <el-col span="24" style="margin-bottom: 15px;margin-left: 10px;font-size: 28px;color: #8c939d">{{ category.name }}类</el-col>
      <el-col span="5" style="margin: 0 10px" v-for="product of category.products" :key="product.id">
        <div class="" style="width: 100%;height: 0;padding-bottom: 100%;position: relative;margin-bottom: 5px">
          <img
            :src="product.image !==null? baseImageUrl + product.image.name:''"
            alt="" style="width: 100%;height: 100%;position: absolute;margin-left: -2px;border-radius: 5px">
        </div>
        <span style="color: #5a5e66">
          {{ product.name }}
        </span>
        <div class=""></div>
        <el-button size="small" style="margin-left: -2px;margin-top: 5px" @click="buyProduct(product)">购买</el-button>
      </el-col>
    </el-row>
    <div style="height: 200px"></div>
  </div>
</template>

<script>
import Navbar from '@/layout/components/Navbar'
import { list } from '@/api/category'
import { saveAll } from '@/api/order'

export default {
  name: 'home',
  components: { Navbar },
  data() {
    return{
      baseImageUrl: process.env.VUE_APP_BASE_API + '/file/get/',
      categories:[]
    }
  },
  beforeMount() {
    list().then(resp=>{
        this.handleCategories(resp.data)
    })
  },
  methods:{
    buyProduct(product) {
      saveAll({data:JSON.stringify([{user:this.$store.getters.user,product:product,address:this.$store.getters.user.address}])}).then(()=>{
        this.$message.success("购买成功,请等待发货")
      })
    },
    handleCategories(data) {
      for (let item of data) {
        if (item.products.length > 0) {
          this.categories.push(item)
        }
        if (item.children !== undefined && item.children.length>0) {
          this.handleCategories(item.children)
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
